<script setup>
  import {payConfig, payOrder, orderConfig, queryOrderInfo} from '@/api/shopping'
  import {t} from '@/locales'
  import { showToast } from 'vant'

  const props = defineProps({
    query: {
      type: Object,
      default: () => {}
    }
  })

  const emits = defineEmits(['reload'])

  const payList = ref([])
  const payMethod = ref('')
  const paySuccessUrl = ref('')
  // stripe支付
  const striptOb = ref({})
  // 支付计时器
  const payTimer = ref(null)
  // 订单心跳
  const orderTimer = ref(null)
  const payEnable = ref(false)
  // 剩余支付时间
  const remainTime = ref('')
  const orderInfo = ref({})
  const orderRule = ref({})

  const btnText = computed(() => {
    let text = ''
    if (remainTime.value) text = ` (${remainTime.value})`
    return t('commodity.quiclPay') + text
  })

   // 格式化时分秒
  function secondsToHms (sec) {
    var hours = Math.floor(sec / 3600);
    var minutes = Math.floor((sec % 3600) / 60);
    var seconds = sec % 60;
    return [hours, minutes, seconds]
      .map(num => num < 10 ? '0' + num : num)
      .filter(Boolean)
      .join(':');
  }
  // 刷下剩余时间
  function getRemainTime () {
    const { orderCancelHour } = orderRule.value
    const { createTime } = orderInfo.value
    // 系统设置的支付时间限制
    const sysPayTime = orderCancelHour || 1
    // 已创建订单时间
    const passSec = parseInt((new Date().getTime() - createTime) / 1000)
    // 已超时支付
    if (passSec > sysPayTime * 3600) {
      payEnable.value = true
      clearInterval(payTimer.value)
      return
    }
    // 剩余时间、秒
    const s = sysPayTime * 3600 - passSec
    remainTime.value = secondsToHms(s)
  }
  // 清除定时器、心跳
  function clearTimer () {
    clearInterval(payTimer.value)
    clearInterval(orderTimer.value)
    orderTimer.value = null
  }
  // 订单规则配置
  function getOrderConfig () {
    orderConfig().then(r => {
      orderRule.value = r.data
    })
  }
  // 获取支付方式
  function getPayList() {
    payConfig().then(r => {
      const {data} = r
      payList.value = data
      data.forEach(it => {
        setPay(it)
      })
    })
  }
  // 实例化stripe
  function initStripe(pkId, clientSecret) {
    const stripe = window.Stripe(pkId)
    const options = {
      clientSecret,
      appearance: {},
    }
    const elements = stripe.elements(options);

    // Create and mount the Payment Element
    const paymentElement = elements.create('payment');
    paymentElement.mount('#payment-element');
    striptOb.value = {
      stripe,
      elements
    }
  }
  // 初始化支付数据、实例化stripe支付
  function setPay(it) {
    const {code, clientId} = it
    payOrder({orderId: props.query.orderId, payMethod: code}).then(r => {
      const {payUrl} = r.data
      if(code==='stripe') {
        initStripe(clientId, payUrl)
      } else {
        paySuccessUrl.value = payUrl
      }
    })
  }
  // 选择支付方式
  function selectPay(it) {
    const {code} = it
    payMethod.value = code
  }
  // stripe支付
  async function stripePay() {
    const {stripe, elements} = striptOb.value
    const {h5Url} = orderRule.value
    const res = await stripe.confirmPayment({
      elements,
      confirmParams: {
        return_url: `${h5Url}/#/shopping?orderId=${props.query.orderId}`
      }
    })
    if(res.error) {
      showToast(error.message)
    }
  }
  // 提交支付
  function toPay() {
    if(!payMethod.value) return showToast(t('commodity.payTip'))
    if(!paySuccessUrl.value) return showToast(t('commodity.paying'))
    if(payMethod.value==='stripe') stripePay()
    if(payMethod.value==='paypal') {
      setTimer()
      window.open(paySuccessUrl.value)
    }
  }
  // 支付后开始心跳检测订单状态
  function setTimer() {
    orderTimer.value = setInterval(() => { getOrderInfo(true) }, 5000)
  }

  defineExpose({toPay})
  // 查询订单信息
  function getOrderInfo (used = false) {
    const { orderId } = props.query
    queryOrderInfo(orderId).then(r => {
      const { status } = r.data
      orderInfo.value = r.data
      if (status === 0) {
        if (!used) payTimer.value = setInterval(getRemainTime, 1000)
      } else {
        // 支付完成，清除清除定时器
        emits('reload', 2)
        clearTimer()
      }
    })
  }
  // 初始化
  function init() {
    getPayList()
    getOrderConfig()
    getOrderInfo()
  }
  // 清除定时器
  onBeforeUnmount(() => {
    clearTimer()
  })

  init()
</script>

<template>
  <div class="pay">
    <div class="pay-con">
      <p class="title">{{$t('commodity.payType')}}</p>
      <p class="no">{{$t('commodity.tradeNo')}}：{{orderInfo.orderCode}}</p>
      <div class="card-list">
        <div :class="['s-card', 'cursor-p', payMethod===it.code?'active':''] " v-for="it in payList" :key="it.id" @click="selectPay(it)">
          <img :src="it.logo"/> {{it.name}}
        </div>
      </div>
      <div class="stripe"  v-show="payMethod==='stripe'">
        <div id="payment-element"/>
      </div>
    </div>
    <div class="submit-cell">
      <van-button
        class="s-btn"
        :disabled="payEnable"
        @click="toPay"
      >
        {{btnText}}
      </van-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
  .pay {
    .pay-con {
      padding: 16px;
      .title {
        font-size: 14px;
      }
      .no {
        font-size: 12px;
        color: #8C8C8C;
        margin: 4px 0 16px;
      }
      .card-list {
        .s-card {
          height: 48px;
          border-radius: 2px;
          font-weight: 600;
          font-size: 14px;
          text-align: center;
          border: 1px  #E5E5E5 solid;
          margin-bottom: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          img {
            width: 24px;
            height: 24px;
          }
          &.active {
            border-color: #262626;
          }
        }
      }
      .stripe {
        padding-top: 10px;
        border-top: 1px solid #E5E5E5;
      }
    }
    .submit-cell {
      padding: 8px 16px;
      border-top: 1px  #E5E5E5 solid;
      position: fixed;
      bottom: 0;
      width: 100%;
      box-sizing: border-box;
    }
  }
</style>